<?php
class Router {
    protected $routes = [];
    
    public function add($url, $controller, $action) {
        $this->routes[$url] = [
            'controller' => $controller,
            'action' => $action
        ];
    }
    
    public function dispatch($url) {
        if (array_key_exists($url, $this->routes)) {
            $controller = $this->routes[$url]['controller'];
            $action = $this->routes[$url]['action'];
            
            $controllerFile = ROOT_PATH . '/app/controllers/' . $controller . '.php';
            
            if (file_exists($controllerFile)) {
                require_once $controllerFile;
                $controllerInstance = new $controller();
                
                if (method_exists($controllerInstance, $action)) {
                    $controllerInstance->$action();
                } else {
                    echo "方法 {$action} 不存在";
                }
            } else {
                echo "控制器 {$controller} 不存在";
            }
        } else {
            echo "路由 {$url} 不存在";
        }
    }
}
?>